package com.homework.interceptor;

import com.homework.content.BaseContext;
import com.homework.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * jwt令牌校验的拦截器
 */
@Slf4j
@Component
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        //1、从请求头中获取令牌
        String token = request.getHeader("authorization");
        log.info(token);
        if (token == null) {
            //没有令牌，响应401状态码
            response.setStatus(401);
            return false;
        }
        //2、校验令牌
        try {
            Map<String, Object> map = JwtUtil.parseToken(token);
            Long userId = Long.valueOf(map.get("userId").toString());
            String role = map.get("role").toString();
            BaseContext.setCurrentId(userId);
            log.info("当前用户id：{}", userId);
            log.info("当前用户角色：{}", role);
            if ("0".equals(role) && !request.getRequestURI().contains("student")){
                response.setStatus(401);
                return false;
            }
            if ("1".equals(role) && !request.getRequestURI().contains("teacher")){
                response.setStatus(401);
                return false;
            }
            if ("2".equals(role) && !request.getRequestURI().contains("admin")){
                response.setStatus(401);
                return false;
            }
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            log.info(ex.getMessage());
            //4、不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }
}
